package com.sunchis.demo.util.server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

/**
 * UDP客户端程序，用于对服务端发送数据，并接收服务端的回应信息
 * @author XuLiang
 *
 */
public class MulticastClient {
	private static String defaultMulticastIp = "224.0.0.4";
	private static int defaultMulticastPort = 6006;
	private static InetAddress multicastGroup;
	
	private byte[] buffer = new byte[4096];
	private static MulticastSocket multicastSocket = null;
	private static DatagramSocket datagramSocket = null;
	
	public static void main(String[] args) {
		MulticastClient multicastClient = null;
		try {
			multicastClient = new MulticastClient(defaultMulticastIp);
			while (true) {
				String message = "Hello! this is message from xl"; 
				multicastClient.send(message);
				Thread.sleep(5000);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			multicastClient.close();
		}
	}
	
	public MulticastClient(String multicastIp) throws Exception {
		new MulticastClient(multicastIp, defaultMulticastPort);
	}
	
	public MulticastClient(String multicastIp, int multicastPort) throws Exception {
		multicastGroup = InetAddress.getByName(multicastIp); 		// 组播地址
		multicastSocket = new MulticastSocket(defaultMulticastPort);
		multicastSocket.joinGroup(multicastGroup);
	}
    
	/**
     * 向指定的组播组发送数据信息 
     * @param data
     * @throws IOException 
     */
    public final void send(String data) throws IOException{
    	byte[] dataBuffer = data.getBytes();
    	DatagramPacket sendPacket = new DatagramPacket(dataBuffer, dataBuffer.length, multicastGroup, defaultMulticastPort);
    	multicastSocket.send(sendPacket);	// 发送数据到组播组中
		System.out.println("数据已发往：" + multicastGroup + "/" + defaultMulticastPort);
    }
    
    /** 
     * 接收从指定的服务端发回的数据 
     */  
//    public final String receive() throws Exception {
//    	datagramSocket = new DatagramSocket();
//        DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);  
//        datagramSocket.receive(receivePacket);
//        String data = new String(receivePacket.getData(), 0, receivePacket.getLength(), "utf-8");       
//        return data;  
//    }
    
    public void close() {
		if (multicastSocket != null) {
			try {
				multicastSocket.leaveGroup(multicastGroup);			// 使用组播套接字的leaveGroup()方法，离开组播组
				multicastSocket.close(); 							// 关闭组播套接字
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("socket closed successfully.");
	}
}
